// Copyright (c) 2022 CHANGLEI. All rights reserved.

import 'dart:async';

import 'package:aircraft_war/bloc/game_state_cubit.dart';
import 'package:aircraft_war/widgets/operation_panel.dart';
import 'package:flame/game.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_grasp/flutter_grasp.dart';

const _overlayKey = 'operationPanel';

/// Created by changlei on 2022/5/17.
///
/// 游戏页面
class GamePage extends StatefulWidget {
  /// 游戏页面
  const GamePage({Key? key}) : super(key: key);

  @override
  State<GamePage> createState() => _GamePageState();
}

class _GamePageState extends CompatibleState<GamePage> {
  late final _stateCubit = GameStateCubit();
  late final StreamSubscription<GameState> _subscription;

  late GameState _state;

  @override
  void initState() {
    super.initState();
    _state = _stateCubit.state;
    _subscription = _stateCubit.stream.listen((newState) {
      if (_state != newState) {
        _state = newState;
        _onNewState(newState);
      }
    });
  }

  @override
  void dispose() {
    _subscription.cancel();
    _stateCubit.close();
    super.dispose();
  }

  void _onNewState(GameState state) {
    final game = _stateCubit.game;
    switch (state) {
      case GameState.idle:
        game.overlays.add(_overlayKey);
        break;
      case GameState.pending:
        game.overlays.add(_overlayKey);
        break;
      case GameState.running:
        game.overlays.remove(_overlayKey);
        break;
      case GameState.pausing:
        game.overlays.add(_overlayKey);
        break;
      case GameState.stopped:
        game.overlays.add(_overlayKey);
        break;
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        final stateCubit = _stateCubit.game.stateCubit;
        switch (_state) {
          case GameState.idle:
          case GameState.pending:
            break;
          case GameState.running:
            stateCubit.pause();
            break;
          case GameState.pausing:
            stateCubit.run();
            break;
          case GameState.stopped:
            stateCubit.pending();
            break;
        }
        return false;
      },
      child: CupertinoPageScaffold(
        child: GameWidget(
          game: _stateCubit.game,
          overlayBuilderMap: <String, OverlayWidgetBuilder>{
            _overlayKey: (context, game) {
              return OperationPanel(
                game: _stateCubit.game,
              );
            },
          },
        ),
      ),
    );
  }
}
